﻿/**

 * Copyright (c) 2015-2016, FastDev 刘强 (fastdev@163.com) & Quincy.

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */


using OF.DistributeService.Core.Common;
using OF.Notify.Entity;
using OF.Notify.Test.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mock
{
    public class TestLinkHead
    {
        public static void Test()
        {
            HeadTailLink<TopicMessage> link = new HeadTailLink<TopicMessage>();
            TVisitHeadTailLink vl = new TVisitHeadTailLink { ClusterId = 0, CollectionId = 0, Link = link };
            Dump("head1", link.GetHead());
            Dump("list1", link.GetList());
            Dump("next1", link.GetNext(link.GetHead()));
            TestVisitUnfinish("TestVisitUnfinish1", vl);
            TestVisitUnfinish("TestVisitUnfinish1", vl);
            TestVisitUnfinish("TestVisitUnfinish1", vl);
            TestVisitFinish("TestVisitFinish1", vl);
            TestVisitError("TestVisitError1", vl);
            link.ForEach((msg) => {
                Util.LogInfo("msg 1:" + BitConverter.ToInt32(msg.body, 0));
            });
            link.Add(new LinkItem<TopicMessage> { Data = new TopicMessage((byte)TopicEnum.SO, BitConverter.GetBytes(1)) });
            Dump("head2", link.GetHead());
            Dump("list2", link.GetList());
            Dump("next2", link.GetNext(link.GetHead()));
            TestVisitUnfinish("TestVisitUnfinish2", vl);
            TestVisitUnfinish("TestVisitUnfinish2", vl);
            TestVisitUnfinish("TestVisitUnfinish2", vl);
            TestVisitFinish("TestVisitFinish2", vl);
            TestVisitError("TestVisitError2", vl);
            link.ForEach((msg) => {
                Util.LogInfo("msg 2 body:" + BitConverter.ToInt32(msg.body, 0));
            });
            link.Add(new LinkItem<TopicMessage> { Data = new TopicMessage((byte)TopicEnum.SO, BitConverter.GetBytes(2)) });
            Dump("head3", link.GetHead());
            Dump("list3", link.GetList());
            Dump("next3", link.GetNext(link.GetHead()));
            TestVisitUnfinish("TestVisitUnfinish3", vl);
            TestVisitFinish("TestVisitFinish3", vl);
            TestVisitError("TestVisitError3", vl);
            link.ForEach((msg) =>
            {
                Util.LogInfo("msg 3 body:" + BitConverter.ToInt32(msg.body, 0));
            });
            link.Add(new LinkItem<TopicMessage> { Data = new TopicMessage((byte)TopicEnum.SO, BitConverter.GetBytes(2)) });
            Dump("head4", link.GetHead());
            Dump("list4", link.GetList());
            Dump("next4", link.GetNext(link.GetHead()));
            TestVisitUnfinish("TestVisitUnfinish4", vl);
            TestVisitFinish("TestVisitFinish4", vl);
            TestVisitError("TestVisitError4", vl);
            link.ForEach((msg) =>
            {
                Util.LogInfo("msg 4 body:" + BitConverter.ToInt32(msg.body, 0));
            });
            Console.Read();
        }

        private static void TestVisitUnfinish(string name, TVisitHeadTailLink tl)
        {
            //tl.Reset();
            tl.Link.IsFull = false;
            var result = tl.VisitAll((msg) =>
            {
                Util.LogInfo(name + ":" + BitConverter.ToInt32(msg.body, 0));
            });
            Util.LogInfo(name + " result:" + result);
        }

        private static void TestVisitError(string name, TVisitHeadTailLink tl)
        {
           // tl.Reset();
            tl.Link.IsFull = false;
            var result = tl.VisitAll((msg) =>
            {
                throw new Exception("TestVisitError");
            });
            Util.LogInfo(name + " result:" + result);
        }

        private static void TestVisitFinish(string name, TVisitHeadTailLink tl)
        {
            //tl.Reset();
            tl.Link.IsFull = true;
            var result = tl.VisitAll((msg) =>
            {
                Util.LogInfo(name + ":" + BitConverter.ToInt32(msg.body, 0));
            });
            tl.Link.IsFull = false;
            Util.LogInfo(name + " result:" + result);
        }

        private static void Dump(string name, List<TopicMessage> list)
        {
            Util.LogInfo(name + ":" + string.Join(" ", list.Select(msg => BitConverter.ToInt32(msg.body, 0))));
        }

        private static void Dump(string name, LinkItem<TopicMessage> linkItem)
        {
            string body = string.Empty;
            if (linkItem == null || linkItem.Data == null || linkItem.Data.body == null)
            {
                body = string.Empty;
            }
            else
            {
                body = BitConverter.ToInt32(linkItem.Data.body, 0).ToString();
            }
            Util.LogInfo(name + ":" + body);
        }
    }

    public class TVisitHeadTailLink
    {
        private LinkItem<TopicMessage> currentItem = null;
        public HeadTailLink<TopicMessage> Link;
        public int CollectionId;
        public int ClusterId;

        private LinkItem<TopicMessage> GetNext(out bool isLinkFull)
        {
            isLinkFull = Link.IsFull;
            LinkItem<TopicMessage> nextItem = Link.GetNext(currentItem);
            if (nextItem != null)
            {
                currentItem = nextItem;
            }
            return nextItem;
        }

        public void Reset()
        {
            currentItem = null;
        }

        public VisitLinkResult VisitAll(Action<TopicMessage> action)
        {
            int collectionId = this.CollectionId;
            while (true)
            {
                bool isLinkFull = false;
                LinkItem<TopicMessage> message = GetNext(out isLinkFull);
                if (message == null)
                {
                    if (isLinkFull)
                    {
                        return VisitLinkResult.Finished;
                    }
                    else
                    {
                        return VisitLinkResult.UnFinish;
                    }
                }
                else
                {
                    try
                    {
                        action(message.Data);
                    }
                    catch (Exception ex)
                    {
                        Util.LogException("ConsumeCollections, DataCollection:", ex);
                    }
                }
            }
        }
    }

    public enum VisitLinkResult
    {
        Finished,
        UnFinish,
        Error
    }
}
